var customAlertTable = function() {
	var validator;
	return {
		init : function() {
			var tableId = "customAlert_table";
			util.initCheckBox(tableId);
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';
			//查询字典信息列表
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "alertCode",
					"value" : $("#id_cusAlertCode").val()
				});
				aoData.push({
					"name" : "alertName",
					"value" : $("#id_cusAlertName").val()
				});
				aoData.push({
					"name" : "alertLevel",
					"value" : $("#id_cusAlertLevel").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			
			$('#customAlert_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/customAlert/getCustomAlert.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return checkBoxDivStr;
					},
					"bSortable" : false
				},
				{
					"data" : "alertCode",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "alertName",
					"bSortable" : false,
					"defaultContent" : "",
					"render" : function(data, type, full, meta) {
							 return '<a class="showDetail" style="cursor:pointer;color:blue;" data-toggle="modal">'+data+'</a>';
						}
				}, {
					"data" : "alertParam",
					"bSortable" : false,
					"defaultContent" : ""
				},{
					"data" : "alertDefinition",
					"bSortable" : false,
					"defaultContent" : ""
				},{
					"data" : "alertLevel",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "alertCategory",
					"bSortable" : false,
					"defaultContent" : ""
				},
				{
					"data" : "updateDateStr",
					"bSortable" : false,
					"defaultContent" : ""
				}
				],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});
			
			//查询
			$("#btn_query").click(function(e) {
				var table = $('#customAlert_table').DataTable();
				table.draw(true);
			});
			//重置查询条件
			$("#btn_reset").click(function(e) {
				$("#id_cusAlertCode").val("");
				$("#id_cusAlertName").val("");
				$("#id_cusAlertLevel").val("");
			});

			//新增
			$("#customAlert_table_add").on('click',function(e){
				e.preventDefault();
				$("#add_title").text("新增自定义告警");
				util.getDictByParentKey(null, 'form_alertLevel', '请选择','main/alertDefinition/findAlertLevelOpt.mvc');
				util.getDictByParentKey("GJCSLB", 'form_alertParam','请选择');
				$("#add-customAlert").modal({show:true,keyboard:false});
			});

			//编辑
			$("#customAlert_table_edit").on('click',function(e){
				e.preventDefault();
				var d = [];
				d = util.getCheckedData("customAlert_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				
				$("#add_title").text("编辑自定义告警");
				util.getDictByParentKey(null, 'form_alertLevel', '请选择','main/alertDefinition/findAlertLevelOpt.mvc');
				util.getDictByParentKey("GJCSLB", 'form_alertParam','请选择');
				var data = [];
				data = getCustomAlertById(util.getCheckedData("customAlert_table")[0].pkId);
				$("#customAlert_id").val(data.pkId);
				$("#alert_definition_id").val(data.alertDefinitionId);
				$("#form_alertCode").val(data.alertCode);
				$("#form_alertName").val(data.alertName);
				$("#form_alertLevel").val(data.alertLevel);
				$("#form_alertParam").val(data.alertParam);
				$("#form_alertDefinition_code").val(data.alertDefinitionCode);
				$("#form_alertDefinition").val(data.alertDefinition);
				$("#form_alertCategory").val("自定义告警");//自定义告警
				$("#comparison_operator_one").val(data.comparisonOperatorOne);
				$("#comparison_operator_two").val(data.comparisonOperatorTwo);
				$("#comparison_value_one").val(data.comparisonValueOne);
				$("#comparison_value_two").val(data.comparisonValueTwo);
				$("#logical_symbol").val(data.logicalSymbol);
				$("#add-customAlert").modal({show:true,keyboard:false});

			});

			$("#customAlert_table").on("click", "a.showDetail",function(e){
				var c = util.getCheckedData("customAlert_table");
				if (c.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				var data = [];
				debugger
				data =getCustomAlertById(util.getCheckedData("customAlert_table")[0].pkId);
				$("#detail_alertCode").text(data.alertCode);
				$("#detail_alertName").text(data.alertName);
				$("#detail_alertLevel").text(data.levelName);
				$("#detail_alertParam").text(data.paramName);
				
				$("#detail_alertDefinition").text(data.alertDefinition);
				
				$("#detail_operator_one").val(data.comparisonOperatorOne);
				$("#detail_operator_two").val(data.comparisonOperatorTwo);
				$("#detail_value_one").val(data.comparisonValueOne);
				$("#detail_value_two").val(data.comparisonValueTwo);
				$("#detail_logical_symbol").val(data.logicalSymbol);
				$("#addID-detail").modal({show:true,keyboard:false});
			});

			$("#addID-detail").on("click", ".close",function(e){
				
				$("#detail_alertCode").text('');
				$("#detail_alertName").text('');
				$("#detail_alertLevel").text('');
				$("#detail_alertParam").text('');
				
				$("#detail_alertDefinition").text('');
				
				$("#detail_operator_one").val('');
				$("#detail_operator_two").val('');
				$("#detail_value_one").val('');
				$("#detail_value_two").val('');
				$("#detail_logical_symbol").val('');
			});


			//删除 -----begin
			$("#customAlert_table_del").on('click', function(){
				var d = [];
				d = util.getCheckedData("customAlert_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中的记录？", "_confirmModal_yes");
					
				}
			});

			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("customAlert_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#customAlert_table').DataTable();
				var currentPage =table.page();
				var selRows = table.rows('.selected');
				$.ajax({
					"type" : "post",
					"url" : "main/customAlert/deleteCustomAlert.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '删除成功！'});
							selRows.remove();
							table.page(currentPage).draw('page');
						}else {
							rmsBox.notify('error', {msg: '删除失败！',delay:3000});
						}
					}
				});
			});



			$("#form_alertParam").change(function(e) {
				debugger
				$("#comparison_operator_one").val("");
				$("#comparison_value_one").val("");
				$("#logical_symbol").val("");
				$("#comparison_operator_two").val("");
				$("#comparison_value_two").val("");
				var key = $(this).children('option:selected').val();
				if(key == 'ALERT_PARAM_L'){
					$("#param_value").css({'display': 'none'});
				}else {
					$("#param_value").css({'display': ''});
				}
				$.ajax({
					"type" : "post",
					"url" : "main/sysDictIndex/getDictByParentKey.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"parentKey" : key
					},
					"success" : function(resp) {
						//debugger
						if(resp&&resp.dict.length>0){
							var alertDefinition_code = resp.dict[0].dictKey;
							var alertDefinition_value = resp.dict[0].dictName;
							$("#form_alertDefinition_code").val(alertDefinition_code);
							$("#form_alertDefinition").val(alertDefinition_value);
						}
					}
				});
				
			});
			//关闭按钮 清空表单
			$("#form_btn_close").click(function(e) {
				$("#customAlert_id").val("");
				$("#alert_definition_id").val("");
				$("#customAlert_form")[0].reset();
				$("#customAlert_form select").val("");
				$("#form_alertDefinition_code").val("");
				$("#form_alertDefinition").val("");
				if (validator) {
					validator.resetForm();
				} 
			});

			function getCustomAlertById(id){
				var data = [];
				$.ajax({
					"type" : "post",
					"url" : "main/customAlert/getCustomAlertById.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : id
					},
					"success" : function(resp) {
						data = resp;
					}
				});
				return data;
			};

			function save(){
				debugger
				var flag = checkParamValue();
				if(!flag){
					alert("不合理的参数范围！");
					return false;
				}
				var table = $('#customAlert_table').DataTable();
				var currentPage =table.page();
				var d = {};
				d['pkId'] = $("#customAlert_id").val();
				d['alertDefinitionId'] = $("#alert_definition_id").val();
				d['alertCode'] = $("#form_alertCode").val();
				d['alertName'] = $("#form_alertName").val();
				d['alertLevel'] =  $("#form_alertLevel").val();
				d['alertParam'] = $("#form_alertParam").val();
				d['alertDefinitionCode'] = $("#form_alertDefinition_code").val();
				d['alertDefinition'] = $("#form_alertDefinition").val();
				d['alertCategory'] = '3';//自定义告警
				d['comparisonOperatorOne'] = $("#comparison_operator_one").val();
				d['comparisonOperatorTwo'] = $("#comparison_operator_two").val();
				d['comparisonValueOne'] = $("#comparison_value_one").val();
				d['comparisonValueTwo'] = $("#comparison_value_two").val();
				d['logicalSymbol'] = $("#logical_symbol").val();
				$.ajax({
					"type" : "post",
					"url" : "main/customAlert/saveOrUpdateCustomAlert.mvc",
					"dataType" : "json",
					"async":false,
					"data" : d,
					"success" : function(resp) {
						debugger
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#form_btn_close").click();
							table.page(currentPage).draw('page');
						}else{
							rmsBox.notify('error', {msg: '保存失败！',delay:3000});
						}
						
					}
				});
				
				
			};

			function checkParamValue(){
				var operatorOne = $("#comparison_operator_one").val();
				var operatorTwo = $("#comparison_operator_two").val();
				var valueOne = $("#comparison_value_one").val();
				var valueTwo = $("#comparison_value_two").val();
				var logicalSymbol = $("#logical_symbol").val();
				var flag = true;
				if(operatorOne!=null&&operatorOne!=""){
					if(valueOne==null||valueOne==""){
						flag = false;
						return flag;
					}
				}else if(operatorOne==null||operatorOne==""){
					if(valueOne!=null&&valueOne!=""){
						flag = false;
						return flag;
					}
					if(logicalSymbol!=null&&logicalSymbol!=""){
						flag = false;
						return flag;
					}
				}

				if(operatorTwo!=null&&operatorTwo!=""){
					if(valueTwo==null||valueTwo==""){
						flag = false;
						return flag;
					}
				}else if(operatorTwo==null||operatorTwo==""){
					if(valueTwo!=null&&valueTwo!=""){
						flag = false;
						return flag;
					}
					if(logicalSymbol!=null&&logicalSymbol!=""){
						flag = false;
						return flag;
					}
				}

				if(operatorOne!=null&&operatorOne!=""&&operatorTwo!=null&&operatorTwo!=""){
					if(logicalSymbol==null||logicalSymbol==""){
						flag = false ;
						return flag;
					}
				}

				if(logicalSymbol == '1') {
					if(valueOne!=null||valueOne!=""&&valueTwo!=null&&valueTwo!=""){
						if(parseFloat(valueOne)>parseFloat(valueTwo)){
							flag = false;
							return flag;
						}
					}
				}

				return flag;


			}
			
			$("#comparison_value_one").bind("keypress", function(event) { 
				//debugger 
    			var event= event || window.event;  
    			var getValue = $(this).val();  
			    //控制第一个不能输入小数点"."  
			    if (getValue.length == 0 && event.which == 46) {  
			        //alert(1)  
			        event.preventDefault();  
			        return;  
			    }  
			    //控制只能输入一个小数点"."  
			    if (getValue.indexOf('.') != -1 && event.which == 46) {  
			        event.preventDefault();  
			        //alert(1)  
			        return;  
			    }  
			    //控制只能输入的值  
			    //alert(event.which);
			    if (event.which && (event.which < 48 || event.which > 57) && event.which != 8 && event.which != 46) {  
			        event.preventDefault();  
			        return;  
			    }  
			}); 

			$("#comparison_value_two").bind("keypress", function(event) { 
				//debugger 
    			var event= event || window.event;  
    			var getValue = $(this).val();  
			    //控制第一个不能输入小数点"."  
			    if (getValue.length == 0 && event.which == 46) {  
			        //alert(1)  
			        event.preventDefault();  
			        return;  
			    }  
			    //控制只能输入一个小数点"."  
			    if (getValue.indexOf('.') != -1 && event.which == 46) {  
			        event.preventDefault();  
			        //alert(1)  
			        return;  
			    }  
			    //控制只能输入的值  
			    //alert(event.which);
			    if (event.which && (event.which < 48 || event.which > 57) && event.which != 8 && event.which != 46) {  
			        event.preventDefault();  
			        return;  
			    }  
			}); 

			$("#comparison_value_one").bind("blur", function(event) {
				debugger  
			    var value = $("#comparison_value_one").val(), reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/ ;  
			    if (reg.test(value)) {  

			    	$("#comparison_value_one").val(value);  
    			} else {
    				$("#comparison_value_one").val("");
    			} 
    			
    		});
    		$("#comparison_value_two").bind("blur", function(event) {
				debugger  
			    var value = $("#comparison_value_two").val(), reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/ ;  
			    if (reg.test(value)) {  
			    	$("#comparison_value_two").val(value);  
    			} else {
    				$("#comparison_value_two").val("");
    			} 
    			
    		});
    		
			/*
			 * validate 自定义验证
			 */
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					errorElement: 'em',
					errorClass: 'redStar',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	alertCode:{
			        		required:true,
			        		checkRepeatCode:true,
			        		checkFormat:true
			        	},
			        	alertCategory:'required',
			        	alertName:'required',
			        	alertLevel:'required',
			        	alertParam:'required',
			        	alertDefinition:'required'
			            },  
			        messages:{  
			        	alertCode:{
			        		required:'不能为空',
			        		checkRepeatCode:'编码重复',
			        		checkFormat:'只能输入英文和数字'
			        	},
			        	alertCategory:'不能为空',
			        	alertName:'不能为空',
			        	alertLevel:'不能为空',
			        	alertParam:'不能为空',
			        	alertDefinition:'不能为空'
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });
			};

			$.validator.addMethod("checkFormat",function(value,element,params){
				var alertCode = $("#form_alertCode").val();
				var reg = /^[A-Za-z0-9]+$/;
				return reg.test(alertCode);
			},"");

			$.validator.addMethod("checkRepeatCode",function(value,element,params){
				var alertCode = $("#form_alertCode").val();
				var pkId = $("#customAlert_id").val();
				var flag = true;
				$.ajax({
					"type" : "post",
					"url" : "main/customAlert/checkRepeatCode.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						'alertCode':alertCode,
						'pkId':pkId
					},
					"success" : function(resp) {
						debugger
						if(resp.msg == false) {
							flag = false;
						}
					}
				});
				return flag;
			},"");
			

			$("#form_customAlert_save").on("click", function(e){
				e.preventDefault();
				debugger
				validator = validateMyForm("customAlert_form");
				if(validator.form()){
					save();
				}else{
					return false;
				}
			});
			
			$(function(){
				$('.search-body input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
				util.getDictByParentKey(null, 'id_cusAlertLevel', '全部','main/alertDefinition/findAlertLevelOpt.mvc');
			});
		}
	};
}();